import pymysql
import os


def wrini(state:str):
    # 连接MySQL数据库
    db = pymysql.connect(host='gz-cdb-qtrebn59.sql.tencentcdb.com', user='root', password='Lx199805037416', database='xxing',port=22713)

    # 设置字符集  防止乱码
    db.set_charset('utf8')

    # 创建游标对象
    cursor = db.cursor()

    # 准备SQL
    sql = 'select * from rate'
    # 执行SQL语句
    cursor.execute(sql)

    #获取结果集
    resultList = cursor.fetchall()

    # 指定要创建的文件的目录
    file_path = 'config.ini'
    i = 0
    # 检查文件路径是否存在
    if not os.path.exists(file_path):
        pass
        print(f'File path {file_path} does not exist, proceed to create.')
    else:
        print(f'File path {file_path} already exists, skip creation.')
    # 执行创建操作
    try:
        with open(file_path, 'w') as f:
            print(f'File {file_path} created successfully.')
    except IOError as e:
        print(f'Error occurred: {e}')

    from configparser import ConfigParser
    from configparser import ConfigParser

    conf = ConfigParser()
    conf.read('config.ini', encoding='utf-8') # 如果新建的话就不需要read,如果修改则需要使用read打开
    for result in resultList:
        conf[i] = {'currencyOne': result[0], 'currencytwo': result[1], 'rateNum': str(result[2])}
        i += 1
    # 保存csv
    with open('config.ini', 'w', encoding='utf-8') as f:
        conf.write(f)

    # 关闭数据库连接
    db.close()
    return "调用成功！"